<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width">
    <title>Channel messaging demo</title>
    <link
      href="http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Lobster+Two"
      rel="stylesheet"
      type="text/css"
    />
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <h1>Channel messaging demo</h1>
    <p id="message-output">Message not yet sent</p>

    <form>
      <label for="message-input">Send a message</label>
      <input type="text" id="message-input" autofocus />
      <button>Send Message</button>
    </form>

    <iframe src="page2.html" width="480" height="320"></iframe>
    <script>
      const input = document.getElementById("message-input");
      const output = document.getElementById("message-output");
      const button = document.querySelector("button");
      const iframe = document.querySelector("iframe");
      const channel = new MessageChannel();
      const port1 = channel.port1;

      // Wait for the iframe to load
      iframe.addEventListener("load", onLoad);

      function onLoad() {
        // Listen for button clicks
        button.addEventListener("click", onClick);
        // Listen for messages on port1
        port1.onmessage = onMessage;
        // Transfer port2 to the iframe
        iframe.contentWindow.postMessage("init", "*", [channel.port2]);
      }

      // Post a message on port1 when the button is clicked
      function onClick(e) {
        e.preventDefault();
        port1.postMessage(input.value);
      }

      // Handle messages received on port1
      function onMessage(e) {
        output.innerHTML = e.data;
        input.value = "";
      }
    </script>
  </body>
</html>
